package com.qf.j2105.config;

import com.qf.j2105.shiro.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShrioConfig {
    @Bean("myRealm")
    //创建自定义安全策略
    public MyRealm myRealm(@Qualifier("hashedCredentialsMatcher") HashedCredentialsMatcher hashedCredentialsMatcher){
        MyRealm myRealm = new MyRealm();
        myRealm.setCredentialsMatcher(hashedCredentialsMatcher);  //设置凭证匹配器
        return  myRealm;
    }
    @Bean("mysecurityManager")
    //创建自定义的securityManager
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("myRealm") MyRealm myRealm){
        DefaultWebSecurityManager securityManager= new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm);   //给安全管理器设置安全策略
        return  securityManager;
    }

    @Bean
    //创建权限拦截器
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("mysecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);  //给权限拦截器设置安全管理器
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauth");
        //定义鉴权逻辑

        Map<String,String> map = new HashMap<>();
//        map.put("/main","authc");
////        map.put("/one","perms[系统管理]");
////        map.put("/two","perms[user_forbidden]");
        map.put("/admin/**","rotes[admin]");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map); //设置过滤规则
        return shiroFilterFactoryBean;
    }

    @Bean("hashedCredentialsMatcher")
    //创建凭证匹配器
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");  //设置hash算法
        hashedCredentialsMatcher.setHashIterations(2);  //设置hash次数
        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);  //设置hash缓存
        return hashedCredentialsMatcher;
    }

}
